import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
  Platform,
  Animated,
} from 'react-native';
import Video from 'react-native-video';

import PxToDp from '../../../utils/PxToDp';
import FontFamilys from '../../../utils/FontFamilys';
import VisitReminder from '../../../containers/VisitRemindContainer';
import fetchCollect from '../../../actions/saleChanceActions';
import LeavingMessage from '../../../containers/LeavingMessageContainer';
import ChangeNote from './ChangeNote';
import ChangeVisitReminderContainer from '../../../containers/changeVisitReminderContainer';
import { fetchMoreVisit, fetchNote, fetchMoreVoices } from '../../../actions/MyCustomerDetailAction';
/* global host */

const stage = ['初步沟通', '已报价', '试驾预约', '到店体验', '已成交', '放弃购买', '其他'];
let timer;
let durations;
class UserBaseInfo extends Component {
  constructor(props) {
    super(props);
    const { data } = this.props;
    const { user } = data;
    this.state = {
      remark: '',
      collect: user.collect,
      remind: {},
      voiceFile: null, // 音频文件
      pause: true,       // 播放/暂停
      progress: new Animated.Value(0),
      play: false,
      gifStop: true,
    };
  }

  _goToChangeVisitReminder() {
    const title = '添加拜访提醒';
    const { data, dispatch, visit, id } = this.props;
    this.props.navigator.push({
      component: ChangeVisitReminderContainer,
      passProps: {
        title,
        data,
        visit,
        dispatch,
        id,
        type: 'add',
      },
    });
  }
  _goToVisitReminderList() {
    const { data, id, dispatch, visit } = this.props;
    this.props.navigator.push({
      component: VisitReminder,
      passProps: {
        id,
        dispatch,
        data,
        visit,
      },
    });
  }
  _goChangeNote(id) {
    const { data, getNote } = this.props;
    const { user } = data;
    const note = getNote ? getNote.note : user.note ? user.note : '';
    this.props.navigator.push({
      component: ChangeNote,
      passProps: {
        dispatch: this.props.dispatch,
        id,
        note,
      },
    });
  }
  _goLeavingMessage() {
    const { dispatch, user } = this.props;
    dispatch(fetchMoreVoices(user.id, () => {
      this.props.navigator.push({
        component: LeavingMessage,
        passProps: { user },
      });
    }));
  }

  _changeCollect() {
    const { id, dispatch } = this.props;
    let collect = this.state.collect;
    if (this.state.collect === 0) {
      collect = 1;
      this.setState({ collect });
    } else {
      collect = 0;
      this.setState({ collect });
    }
    dispatch(fetchCollect(id, collect));
  }

  _voicePaused() {
    let count = 0;

    this.setState({
      play: true,
      pause: !this.state.pause,
      gifStop: true,
    }, () => {
      timer = setInterval(() => {
        count += 1;
        if (count > durations) {
          clearInterval(timer);
          this.setState({ gifStop: false });
        }
      }, 1000);
    });
  }

  componentWillMount() {
    const { dispatch, user } = this.props;
    const remark = user.note ? user.note : '暂无备注';
    const voice = user ? user.voicemsg ? user.voicemsg ? user.voicemsg.file : null : null : null;
    const voiceFile = `${host}/static/${voice}`;

    this.setState({
      remark,
      voiceFile,
    });

    dispatch(fetchMoreVisit(user.id));
    dispatch(fetchNote(user.id));
  }

  componentWillUnmount() {
    clearInterval(timer);
  }

  render() {
    const { id, getNote, visit, user, userType } = this.props;
    const { reminds } = visit;
    const remind = reminds ? reminds[0] : null;

    // const voiceText = this.state.pause ? '' : '';
    // const note = getNote.note ? getNote.note : this.state.remark ? this.state.remark : '暂无备注';

    let name = user.username;
    let sex = '';
    if (name) {
      const length = name.length;
      name = name.substring(length - 2, length);
    }
    durations = user ? user.voicemsg ?
          user.voicemsg ? user.voicemsg.seconds : null : null : null;
    const showDuration = `${durations}"`;

    const bgColor = this.state.play ? 'transparent' : '#f65252';
    let stageText = '';

    if (this.props.stageObj) {
      stageText = stage[this.props.stageObj - 1];
    } else if (user.stage) {
      stageText = stage[user.stage - 1];
    }

    sex = (user && user.sex === '男' ? require('../../../img/home/cule-list-men.png') : require('../../../img/home/cule-list-wamen.png'));
    const showgif = !this.state.pause && this.state.gifStop;

    return (
      <View>
        <View style={[styles.line, styles.lineTop]} />

        <View style={styles.infoSection}>
          <View style={[styles.between, styles.row]}>
            <View style={[styles.row, styles.between, { width: '100%' }]}>
              <View style={[styles.row, styles.infoL]}>
                <View style={[styles.nameWrapper]}>
                  <Text style={styles.nameIcon}>{name}</Text>
                </View>
                <View>
                  <View style={[styles.row, { alignItems: 'center', marginBottom: PxToDp(4) }]}>
                    <Text style={[styles.name]}>{user.username}</Text>
                    <View style={styles.sexWrapper}>
                      <Image source={sex} />
                    </View>
                    {
                      stageText ?
                        <View style={styles.stageWrapper}>
                          <Text style={styles.stage}>{stageText}</Text>
                        </View> :
                      null
                    }
                  </View>
                  <View style={styles.row}>
                    <Text style={styles.loginTime}>最近登录：</Text>
                    <Text style={styles.loginTime}>{user.login_at}</Text>
                  </View>
                </View>
              </View>
              <TouchableOpacity
                activeOpacity={0.8}
                onPress={() => this._changeCollect()}
              >
                { this.state.collect ?

                  <Image source={require('../../../img/home/hStarFocus.png')} />
                :
                  <Image source={require('../../../img/home/hStarNormal.png')} />
              }
              </TouchableOpacity>
            </View>
          </View>
          <View
            style={[
              styles.row, styles.start, styles.top14, { flexWrap: 'wrap' }]}
          >
            <Text style={[styles.option]}>{user.phone}</Text>
            <Text style={[styles.option]}>{user.address}</Text>
            <Text style={[styles.option]}>{user.age}岁</Text>
            <Text style={[styles.option, styles.licenseNumber]}>{user.has_plate ? '有车号' : '无车号'}</Text>
            <Text style={[styles.option]}>{user.buy_at}</Text>
            {
              user.budget_value ?
                <Text style={[styles.option]}>{user.budget_value}</Text> :
              null
            }
            {
              user.buy_method ?
                <Text style={[styles.option]}>{user.buy_method}</Text> :
               null
            }
          </View>
          {userType === 'myCustomer' && remind ?
            <View>
              <View style={[styles.line, styles.visitMrg]} />
              <TouchableOpacity
                style={[styles.switch, styles.row, styles.between]}
                activeOpacity={0.6}
                onPress={() => this._goToVisitReminderList()}
              >
                <View style={[styles.row, styles.between, { width: '100%' }]}>
                  <View style={[styles.row, { alignItems: 'center' }]}>
                    <Image style={styles.visitImg} source={require('../../../img/detail/dtVisit.png')} />
                    <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>拜访：</Text>

                  </View>
                  <View style={[styles.row, { alignItems: 'center' }]}>
                    <Text style={[styles.font12]}>{remind.week} {remind.visit_at}</Text>
                    <Image style={styles.nextIcon} source={require('../../../img/next.png')} />
                  </View>
                </View>
              </TouchableOpacity>
            </View>
            :
            userType === 'myCustomer'
            ?
              <View>
                <View style={[styles.line, styles.visitMrg]} />
                <TouchableOpacity
                  style={[styles.switchAdd, styles.row, styles.between]}
                  activeOpacity={0.6}
                  onPress={() => this._goToChangeVisitReminder()}
                >
                  <View style={[styles.row, styles.remindList]}>
                    <View style={[styles.row, { alignItems: 'center' }]}>
                      <Image style={styles.visitImg} source={require('../../../img/detail/dtVisit.png')} />
                      <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>拜访：</Text>
                    </View>
                    <View style={[styles.row, styles.addRemind]}>
                      <Text style={styles.addIcon}>+</Text>
                      <Text style={styles.addText}>添加</Text>
                    </View>
                  </View>
                </TouchableOpacity>
              </View>

               : null
          }
          {userType === 'myCustomer' && getNote.note ?

            <View>
              <View style={[styles.line]} />
              <TouchableOpacity
                style={[styles.row, styles.switch, styles.between]}
                activeOpacity={0.6}
                onPress={() => this._goChangeNote(user.id)}
              >
                <View style={[styles.row, { alignItems: 'center' }]}>
                  <Image style={styles.visitImg} source={require('../../../img/detail/dtEdit.png')} />
                  <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>备注：</Text>
                </View>
                <View style={[styles.row, { alignItems: 'center' }]}>
                  <Text
                    style={[styles.font12, styles.noteT]}
                    numberOfLines={1}
                  >
                    {getNote.note}
                  </Text>
                  <Image style={[styles.star, styles.nextIcon]} source={require('../../../img/next.png')} />
                </View>
              </TouchableOpacity>
            </View>

            : userType === 'myCustomer' ?
              <View>
                <View style={[styles.line]} />
                <TouchableOpacity
                  style={[styles.row, styles.switchAdd, styles.between]}
                  activeOpacity={0.6}
                  onPress={() => this._goChangeNote(id)}
                >
                  <View style={[styles.row, styles.remindList]}>
                    <View style={[styles.row, { alignItems: 'center' }]}>
                      <Image style={styles.visitImg} source={require('../../../img/detail/dtEdit.png')} />
                      <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>备注：</Text>
                    </View>
                    <View style={[styles.row, styles.addRemind]}>
                      <Text style={styles.addIcon}>+</Text>
                      <Text style={styles.addText}>添加</Text>
                    </View>
                  </View>
                </TouchableOpacity>
              </View>
               : null
          }
          {user.voicemsg ?
            <View>
              {
                userType === 'myCustomer'
                ?
                  <View style={[styles.line]} />
                :
                  <View style={[styles.line, styles.visitMrg]} />
              }

              <View style={[styles.row, styles.switch, styles.between]}>
                <View style={[styles.row, styles.voiceV]}>
                  <Image style={styles.visitImg} source={require('../../../img/detail/dtVoice.png')} />
                  <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>留言：</Text>
                </View>
                <TouchableOpacity
                  activeOpacity={0.6}
                  onPress={() => this._goLeavingMessage()}
                  style={[styles.between, { justifyContent: 'center' }]}
                >
                  <View style={[styles.row, { alignItems: 'center' }]}>
                    {
                    showgif ?
                      <Image
                        style={styles.voiceGif}
                        source={require('../../../img/home/voice1.gif')}
                      /> :
                      <Image
                        style={styles.voiceGif}
                        source={require('../../../img/home/soundIcon.png')}
                      />
                  }
                    <TouchableOpacity
                      style={styles.row}
                      activeOpacity={1}
                      onPress={() => this._voicePaused()}
                    >
                      <Image style={styles.triangle} source={require('../../../img/home/triangle3.png')} />
                      <View
                        style={[styles.voiceWrapper]}
                      >
                        <Text style={[styles.voiceText]} />
                      </View>
                      <View style={{ marginLeft: PxToDp(5) }}>
                        <View style={[styles.redDot, { backgroundColor: bgColor }]} />
                        <Text style={styles.duration}>{showDuration}</Text>
                      </View>
                    </TouchableOpacity>
                    <Image style={[styles.star, styles.nextIcon]} source={require('../../../img/next.png')} />
                  </View>
                </TouchableOpacity>
              </View>
            </View>

            :
            <View>
              {
                userType === 'myCustomer'
                ?
                  <View style={[styles.line]} />
                :
                  <View style={[styles.line, styles.visitMrg]} />
              }
              <View style={[styles.row, styles.switch, styles.between, styles.voiceView]}>

                <View style={styles.row}>
                  <Image style={styles.visitImg} source={require('../../../img/detail/dtVoice.png')} />
                  <Text style={[styles.font14, { marginLeft: PxToDp(10) }]}>留言：</Text>
                </View>
                <Text style={styles.addText}>暂无</Text>
              </View>
            </View>

          }
          {
            this.state.voiceFile ?
              <Video
                source={{ uri: this.state.voiceFile }}
                volume={1.0}
                paused={this.state.pause}
                playInBackground
              /> : null
          }
        </View>
        <View style={styles.line} />
      </View>
    );
  }
 }

const styles = StyleSheet.create({
  row: {
    flexDirection: 'row',
  },
  start: {
    justifyContent: 'flex-start',
  },
  between: {
    justifyContent: 'space-between',
  },
  infoSection: {
    width: '100%',
    backgroundColor: '#fff',
    paddingLeft: PxToDp(20),
    paddingRight: PxToDp(20),
  },
  infoL: {
    paddingTop: PxToDp(17),
  },
  nameWrapper: {
    width: PxToDp(38),
    height: PxToDp(38),
    marginRight: PxToDp(6),
    borderRadius: PxToDp(19),
    backgroundColor: '#a978e5',
    alignItems: 'center',
    justifyContent: 'center',
  },
  nameIcon: {
    color: '#fff',
    fontSize: PxToDp(12),
  },
  loginTime: {
    color: '#999',
    fontSize: PxToDp(10),
  },
  sexWrapper: {
    width: PxToDp(24),
    height: PxToDp(14),
    marginLeft: PxToDp(14),
    justifyContent: 'center',
    alignItems: 'center',
    paddingBottom: Platform.OS === 'ios' ? 0 : PxToDp(2),
  },
  stageWrapper: {
    height: PxToDp(17),
    marginLeft: PxToDp(4),
    paddingLeft: PxToDp(12),
    paddingRight: PxToDp(12),
    paddingTop: PxToDp(3),
    paddingBottom: PxToDp(3),
    backgroundColor: '#efefef',
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: PxToDp(8),
  },
  stage: {
    color: '#8b8c8e',
    fontSize: PxToDp(10),
  },
  option: {
    marginTop: PxToDp(6),
    paddingLeft: PxToDp(8),
    paddingRight: PxToDp(8),
    paddingTop: PxToDp(2),
    height: PxToDp(22),
    color: '#ffffff',
    backgroundColor: '#D6CEAA',
    borderRadius: PxToDp(1),
    fontSize: PxToDp(12),
    fontFamily: FontFamilys(),
    alignItems: 'center',
    marginRight: PxToDp(6),
  },
  top14: {
    marginTop: PxToDp(14),
  },
  switch: {
    width: '100%',
    paddingTop: PxToDp(14),
    paddingBottom: PxToDp(14),
  },
  switchAdd: {
    width: '100%',
    paddingTop: PxToDp(11),
    paddingBottom: PxToDp(11),
  },
  font14: {
    fontSize: PxToDp(14),
    color: '#333',
    fontFamily: FontFamilys(),
  },
  font12: {
    fontSize: PxToDp(12),
    color: '#999',
  },
  remindList: {
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%',
    paddingRight: PxToDp(10),
  },
  addIcon: {
    marginRight: PxToDp(4),
    marginBottom: PxToDp(2),
    color: '#999',
    fontSize: PxToDp(18),
  },
  addText: {
    color: '#999',
    fontSize: PxToDp(13),
  },
  addRemind: {
    alignItems: 'center',
    borderColor: '#ececec',
    borderRadius: PxToDp(2),
    borderStyle: 'solid',
    borderWidth: PxToDp(1),
    paddingLeft: PxToDp(15),
    paddingRight: PxToDp(13),
    height: PxToDp(28),
  },
  voiceWrapper: {
    justifyContent: 'center',
    width: PxToDp(180),
    height: PxToDp(38),
    backgroundColor: '#418cff',
    borderRadius: PxToDp(2),
    zIndex: 888,
    marginLeft: PxToDp(-3),
  },
  voiceText: {
    color: '#c4d2ff',
    fontSize: PxToDp(12),
    fontFamily: FontFamilys(),
    marginLeft: PxToDp(60),
  },
  redDot: {
    marginLeft: PxToDp(3),
    width: PxToDp(7),
    height: PxToDp(7),
    backgroundColor: '#f65252',
    borderRadius: PxToDp(4),
    marginTop: PxToDp(2),
  },
  name: {
    fontFamily: FontFamilys(),
    fontSize: PxToDp(18),
    color: '#000000',
  },
  visitImg: {
    height: PxToDp(18),
    width: PxToDp(16),
  },
  voiceView: {
    paddingRight: PxToDp(10),
  },
  voiceV: {
    alignItems: 'center',
  },
  triangle: {
    marginTop: PxToDp(5),
    marginLeft: PxToDp(5),
  },
  line: {
    height: PxToDp(0.5),
    width: '100%',
    backgroundColor: '#e4e4e4',
  },
  lineTop: {
    marginTop: PxToDp(6),
  },
  voiceGif: {
    position: 'absolute',
    left: PxToDp(30),
    zIndex: 999,
    width: PxToDp(11),
    height: PxToDp(15),
  },
  duration: {
    color: '#121212',
    fontSize: PxToDp(13),
    fontFamily: FontFamilys(),
    marginTop: PxToDp(4),
  },
  visitMrg: {
    marginTop: PxToDp(21),
  },
  nextIcon: {
    marginLeft: PxToDp(7),
  },
  noteT: {
    maxWidth: PxToDp(157),
  },
});

export default UserBaseInfo;
